﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;

namespace BW.WMS.Web.Hubs
{
    [AllowAnonymous] // 临时允许匿名访问进行测试
    public class DashboardHub : Hub
    {
        // 客户端连接时触发
        public override async Task OnConnectedAsync()
        {
            await Clients.All.SendAsync("UserConnected", Context.ConnectionId);
            await base.OnConnectedAsync();
        }

        // 客户端断开连接时触发
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await Clients.All.SendAsync("UserDisconnected", Context.ConnectionId);
            await base.OnDisconnectedAsync(exception);
        }

        // =========================
        // 仪表盘专用方法
        // =========================

        // 加入仪表盘组
        public async Task JoinDashboardGroup()
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, "Dashboard");
            await Clients.Caller.SendAsync("JoinedDashboard", "已连接到仪表盘实时数据");
        }

        // 离开仪表盘组
        public async Task LeaveDashboardGroup()
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, "Dashboard");
            await Clients.Caller.SendAsync("LeftDashboard", "已断开仪表盘连接");
        }

        // 发送库存概览统计数据
        public async Task SendOverviewStats(object data)
        {
            await Clients.Group("Dashboard").SendAsync("OverviewStatsUpdated", data);
        }

        // 发送入库分类数据
        public async Task SendInboundCategory(object data)
        {
            await Clients.Group("Dashboard").SendAsync("InboundCategoryUpdated", data);
        }

        // 发送最近入库记录
        public async Task SendRecentInboundRecords(object data)
        {
            await Clients.Group("Dashboard").SendAsync("RecentInboundRecordsUpdated", data);
        }

        // 发送快速导航数据
        public async Task SendQuickNavigation(object data)
        {
            await Clients.Group("Dashboard").SendAsync("QuickNavigationUpdated", data);
        }

        // 发送完整仪表盘数据
        public async Task SendDashboardData(object data)
        {
            await Clients.Group("Dashboard").SendAsync("DashboardDataUpdated", data);
        }

        // 客户端请求刷新数据
        public async Task RequestDataRefresh()
        {
            await Clients.Caller.SendAsync("DataRefreshRequested", DateTime.Now);
            // 可以在这里触发数据服务的手动更新
        }

        // =========================
        // 通用消息方法
        // =========================

        // 发送消息给所有客户端
        public async Task SendMessage(string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", message);
        }

        // 发送消息给指定组
        public async Task SendMessageToGroup(string groupName, string message)
        {
            await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
        }

        // =========================
        // 库存管理专用方法
        // =========================

        // 发送库存数据更新
        public async Task UpdateInventoryData(object data)
        {
            await Clients.All.SendAsync("InventoryDataUpdated", data);
        }

        // 发送入库统计数据
        public async Task UpdateInboundStats(object data)
        {
            await Clients.All.SendAsync("InboundStatsUpdated", data);
        }

        // 发送出库统计数据
        public async Task UpdateOutboundStats(object data)
        {
            await Clients.All.SendAsync("OutboundStatsUpdated", data);
        }

        // =========================
        // 系统通知方法
        // =========================

        // 发送系统通知
        public async Task SendSystemNotification(string message)
        {
            await Clients.All.SendAsync("SystemNotification", message);
        }

        // 发送操作日志通知
        public async Task SendOperationLog(object logData)
        {
            await Clients.All.SendAsync("OperationLogReceived", logData);
        }

        // 发送库存预警
        public async Task SendStockWarning(object warningData)
        {
            await Clients.All.SendAsync("StockWarningReceived", warningData);
        }

        // =========================
        // 数据同步方法
        // =========================

        // 同步概览统计数据
        public async Task SyncOverviewStats(object data)
        {
            await Clients.Others.SendAsync("OverviewStatsUpdated", data);
        }

        // 同步入库分类数据
        public async Task SyncInboundCategory(object data)
        {
            await Clients.Others.SendAsync("InboundCategoryUpdated", data);
        }

        // 同步最近记录数据
        public async Task SyncRecentRecords(object data)
        {
            await Clients.Others.SendAsync("RecentInboundRecordsUpdated", data);
        }

        // =========================
        // 用户状态管理
        // =========================

        // 加入特定数据组（用于DataV等特殊用途）
        public async Task JoinDataVGroup(string groupName = "DataVUsers")
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
            await Clients.Caller.SendAsync("JoinedGroup", groupName);
        }

        // 离开特定数据组
        public async Task LeaveDataVGroup(string groupName = "DataVUsers")
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
            await Clients.Caller.SendAsync("LeftGroup", groupName);
        }

        // =========================
        // 心跳和状态检测
        // =========================

        // 发送心跳信号
        public async Task SendHeartBeat()
        {
            await Clients.All.SendAsync("HeartBeat", new
            {
                Timestamp = DateTime.Now,
                ServerStatus = "Running",
                Message = "Dashboard service is active"
            });
        }

        // 获取连接状态
        public async Task GetConnectionStatus()
        {
            await Clients.Caller.SendAsync("ConnectionStatus", new
            {
                ConnectionId = Context.ConnectionId,
                ConnectedAt = DateTime.Now,
                Status = "Connected"
            });
        }

        // =========================
        // 错误处理
        // =========================

        // 发送错误信息
        public async Task SendError(string errorMessage, string errorCode = null)
        {
            await Clients.Caller.SendAsync("ErrorReceived", new
            {
                Message = errorMessage,
                Code = errorCode,
                Timestamp = DateTime.Now
            });
        }

        // =========================
        // 批量操作方法
        // =========================

        // 批量发送仪表盘数据
        public async Task SendBatchDashboardData(object overviewStats, object inboundCategory, object recentRecords, object quickNavigation)
        {
            var tasks = new[]
            {
                Clients.Group("Dashboard").SendAsync("OverviewStatsUpdated", overviewStats),
                Clients.Group("Dashboard").SendAsync("InboundCategoryUpdated", inboundCategory),
                Clients.Group("Dashboard").SendAsync("RecentInboundRecordsUpdated", recentRecords),
                Clients.Group("Dashboard").SendAsync("QuickNavigationUpdated", quickNavigation)
            };

            await Task.WhenAll(tasks);

            // 发送完整数据包
            await Clients.Group("Dashboard").SendAsync("DashboardDataUpdated", new
            {
                OverviewStats = overviewStats,
                InboundCategory = inboundCategory,
                RecentRecords = recentRecords,
                QuickNavigation = quickNavigation,
                Timestamp = DateTime.Now
            });
        }

        // =========================
        // 自定义事件处理
        // =========================

        // 处理客户端的自定义请求
        public async Task HandleCustomRequest(string requestType, object requestData)
        {
            switch (requestType.ToLower())
            {
                case "refresh_overview":
                    await Clients.Caller.SendAsync("RefreshOverviewRequested", requestData);
                    break;
                case "refresh_category":
                    await Clients.Caller.SendAsync("RefreshCategoryRequested", requestData);
                    break;
                case "refresh_records":
                    await Clients.Caller.SendAsync("RefreshRecordsRequested", requestData);
                    break;
                case "refresh_all":
                    await Clients.Caller.SendAsync("RefreshAllRequested", requestData);
                    break;
                default:
                    await SendError($"未知的请求类型: {requestType}", "UNKNOWN_REQUEST_TYPE");
                    break;
            }
        }
    }
}